package com.zoe.onelink.sentinel.handler;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.adapter.servlet.config.WebServletConfig;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.zoe.onelink.sentinel.vo.SentinelErrorVO;
import org.springframework.beans.factory.InitializingBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-04-19
 */
public class OnelinkUrlBlockHandler implements UrlBlockHandler, InitializingBean {

    public static final String ERROR_RESULT = JSON.toJSONString(SentinelErrorVO.failure("30020", "Api limiting"));

    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws IOException {

        response.setStatus(WebServletConfig.getBlockPageHttpStatus());
        PrintWriter writer = response.getWriter();
        writer.write(ERROR_RESULT);
        writer.flush();
        writer.close();

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        WebCallbackManager.setUrlBlockHandler(this);
    }
}
